<template>
    <el-select
        :v-model="value"
        v-bind="$attrs"
        :value-key="valueKey ? valueKey : ''"
        :filterable="!!searchKey || filterable"
        :remote="!!searchKey"
        :clearable="clearable"
        :multiple="multiple"
        collapse-tags
        reserve-keyword
        :loading="loading"
        :popper-append-to-body="popperAppendToBody"
        :remote-method="remoteMethod"
        :url="url"
        @change="changeEvent"
    >
        <el-option
            v-for="option in options"
            :key="option[props.key]"
            :label="option[props.value]"
            :value="valueKey ? option : option[props.key] || ''"
        />
    </el-select>
</template>

<script lang="ts">
/**
 * @Description: 下拉组件
 */
import { defineComponent, reactive, PropType, toRefs } from 'vue'
import { getItemAutocompleteApi } from '@/api/common'
import { split, zipObjectDeep, fill, compact } from 'lodash-es'
interface Options {
  key: number | string
  value: string
}
export default defineComponent({
	name: 'GSelect',
	props: {
		// 是否插入body
		popperAppendToBody: {
			type: Boolean,
			default: false
		},
		// 如果设置了该属性，执行请求下拉数据（不是autocomplete）
		reload: {
			type: String,
			default: ''
		},
		// 如果设置了该属性，绑定值为对象
		valueKey: {
			type: String,
			default: ''
		},
		// 搜索内容的key，如果设置了该属性，会启用远程搜索
		searchKey: {
			type: String,
			default: ''
		},
		// 是否可搜索
		filterable: {
			type: Boolean,
			default: true
		},
		// 是否可清除
		clearable: {
			type: Boolean,
			default: true
		},
		// 是否可多选
		multiple: {
			type: Boolean,
			default: false
		},
		// 下拉数据
		options: {
			type: Array as PropType<Options[]>,
			default: () => []
		},
		// 绑定值
		value: {
			type: [String, Number, Object],
			default: ''
		},
		// 默认id，name，如果是key value，传入props="{key: 'key', value: 'value'}"
		props: {
			type: Object,
			default: () => {
				return {
					key: 'id',
					value: 'name'
				}
			}
		},
		// 后台接口的url
		url: {
			type: String,
			default: ''
		}
	},
	emits: ['update:value'],
	setup(props, { emit }) {
		// // 请求下拉数据
		// function reloadOptions() {}

		// if (props.reload) {
		//   reloadOptions()
		// }
		const select = reactive({
			loading: false,
			optionList: props.options
		})
		// console.log('options---', props.options);

		// 远程搜索
		const remoteMethod = (query: string) => {
			// console.log('url=====', props.url)
			// console.log('query=====', query)
			if (query.trim() !== '') {
				const _url = split(props.url, '|')
				// console.log('_url----', _url);
				const keyArr = compact(split(_url[1], ','))
				// console.log('_key_arr----', _key_arr);
				const valArr = fill(Array(keyArr.length), query)
				// console.log('_val_arr----', _val_arr);
				const params = zipObjectDeep(keyArr, valArr)
				// console.log('params----', params);
				select.loading = true
				getItemAutocompleteApi(_url[0], params).then((res: any) => {
					console.log('res---auto----', res)

					select.loading = false
					select.optionList = res.result.map((item) => {
						return { id: item.researchOrgId, name: item.researchOrgName }
					})
				})
			} else {
				select.optionList = []
			}
		}
		// 选中值改变
		const changeEvent = (val: any) => {
			emit('update:value', val)
		}

		return {
			...toRefs(select),
			changeEvent,
			remoteMethod
		}
	}
})
</script>
